import Joi from 'joi';

/**
 * 移除 Joi 的 Schema 的 required / default 属性
 * @param {Object} Joi Schema 对象
 * @return {Object} Joi Schema 对象
 */
export default function joiOmit(
	schema,
	omitField = { required: true, defualt: true, allow: false }
) {
	let ret;
	switch (schema.type) {
		case 'string':
			ret = Joi.string();
			break;
		case 'number':
			ret = Joi.number();
			break;
		case 'date':
			ret = Joi.date();
			break;
		case 'boolean':
			ret = Joi.boolean();
			break;
		case 'array':
			ret = Joi.array().items(joiOmit(schema.$_terms.items[0], omitField));
			break;
		case 'any':
			ret = Joi.any();
			break;
		default:
			ret = Joi.object();
			// eslint-disable-next-line no-unused-expressions
			schema.$_terms.keys?.forEach(({ key, schema }) => {
				ret = ret.append({
					[key]: joiOmit(schema),
				});
			});
	}

	schema._rules.forEach(x => {
		switch (x.method) {
			case 'custom':
				ret = ret.custom(x.args.method, x.args.description);
				break;
		}
	});

	if (!omitField.allow && schema._valids && !schema._flags.empty) {
		ret = ret.allow(...Array.from(schema._valids._values));
	}

	for (const [method, setting] of Object.entries(schema._flags)) {
		switch (method) {
			case 'default':
				if (
					(!schema._flags.empty && omitField.defualt) ||
					setting === undefined
				) {
					continue;
				}
				break;
			case 'presence':
				if (omitField.required && schema._flags.presence === 'required') {
					continue;
				}
				break;
		}
		ret = ret[method](setting);
	}

	return ret;
}
